package com.gcl.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gcl.usercenter.exception.BusinessException;
import com.gcl.usercenter.common.ErrorCode;
import com.gcl.usercenter.mapper.UserMapper;
import com.gcl.usercenter.model.User;
import com.gcl.usercenter.service.UserService;
//import jakarta.annotation.Resource;
//import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    private UserMapper userMapper;

    private static final String salt = "amadeus";
    public static final String USER_LOGIN_STATE = "userLoginState";

    @Override
    public User login(String userAccount, String userPassword, HttpServletRequest request) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isAllBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号小于4位");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码小于8位");
        }
//        把输入的密码加密，不用解密存入的密码
        String password = DigestUtils.md5DigestAsHex((salt + userPassword).getBytes());
        //查询用户是否存在
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", password);
        //userMapper.selectList(queryWrapper);
        User user = this.getOne(queryWrapper);
        if (user == null) {
//            log.info("login failed,userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号和密码不匹配");
        }
        //脱敏
        User safetyUser = getSafetyUser(user);
        //设置登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, safetyUser);
        return safetyUser;
    }

    public User getSafetyUser(User user) {
        if (user == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR,"");
        }
        User safetyUser = new User();
        safetyUser.setId(user.getId());
        safetyUser.setUsername(user.getUsername());
        safetyUser.setUserAccount(user.getUserAccount());
        safetyUser.setAvatarUrl(user.getAvatarUrl());
        safetyUser.setGender(user.getGender());
        safetyUser.setPhone(user.getPhone());
        safetyUser.setEmail(user.getEmail());
        safetyUser.setUserStatus(user.getUserStatus());
        safetyUser.setCreateTime(user.getCreateTime());
        return safetyUser;
    }

    @Override
    public int uerLogout(HttpServletRequest request) {
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }

    @Override
    public long register(String userAccount, String userPassword, String checkPassword) {
        if (StringUtils.isAllBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号小于4位");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码小于8位");
        }
        if (!Objects.equals(userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"两次密码不一致");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = this.count(queryWrapper);//count是计数函数
        //检测账号是否已被使用
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号已被占用");
        }
        String pattern = "^(\\w+)$";
        if (!userAccount.matches(pattern)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数出现特殊字符");
        }
        //密码加盐,加密
//        userPassword += salt;
//        try {
//            // 获取密码的字节数组
//            byte[] passwordBytes = userPassword.getBytes();
//            // 使用MD5算法对字节数组进行加密
//            MessageDigest md = MessageDigest.getInstance("MD5");
//            byte[] hashedBytes = md.digest(passwordBytes);
//            // 转换为十六进制表示
//            StringBuilder sb = new StringBuilder();
//            for (byte hashedByte : hashedBytes) {
//                sb.append(String.format("%02x", hashedByte));
//            }
//            String hashedPassword = sb.toString();
//            // 输出加密后的密码
//            System.out.println("加密后的密码：" + hashedPassword);
//            userPassword=hashedPassword;
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//        }
        //加密
        String password = DigestUtils.md5DigestAsHex((salt + userPassword).getBytes());

        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(password);
//        userMapper.insert(user);
        boolean result = this.save(user);
        if (!result) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"");
        }
        return user.getId();
    }



}
